# encoding=utf-8

import subprocess


def run_command(cmd):
    return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE).stdout.decode('utf-8')


def set_port_mode(port: int, in_mode: bool):
    if in_mode:
        cmd = "gpio mode {} in".format(port)
    else:
        cmd = "gpio mode {} out".format(port)

    return run_command(cmd)


def set_port_level(port: int, is_up: bool):
    if is_up:
        cmd = "gpio mode {} up".format(port)
    else:
        cmd = "gpio mode {} down".format(port)

    return run_command(cmd)


def read_port(port: int):
    cmd = "gpio read {}".format(port)
    port_level = run_command(cmd)
    return int(port_level.strip())


def init_gpio_port(w_pi_port: int):
    b1 = set_port_mode(w_pi_port, True)
    b2 = set_port_level(w_pi_port, True)

    return (b1 == "") and (b2 == "")


if __name__ == '__main__':
    import time
    w_port = 3
    b_init = init_gpio_port(w_port)

    if b_init:
        while True:
            level = read_port(w_port)

            if level == 0:
                print("Crash object")

            print("Present level is:", level)
            time.sleep(1)